﻿using Microsoft.Win32;
using Sunny.UI;
using System;
using System.Drawing;
using System.ServiceModel;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using Timer = System.Timers.Timer;

namespace Form1
{
    public partial class Form1 : Form
    {
        private UILineOption option;
        private SerialClass serialPort;
        private UILineSeries _lineSeries1;
        private UILineSeries _lineSeries2;
        private UILineSeries _lineSeries3;
        private Timer _testTimer;
        private bool _isStartTest = false;
        private int _testLineIndex = 1;
        private int _timeSum = 0;
        private TestData _thisData;

        public Form1()
        {
            InitializeComponent();
            Control.CheckForIllegalCrossThreadCalls = false;
            InitLineChart();
            _testTimer = new Timer();
            _testTimer.Elapsed += _testTimer_Elapsed;

            // 发送的查询指令
            sendTextBox.Text = "64 69 03 5E 4E";

            // 默认查询一遍串口
            uiButton3_Click(null,null);
        }

        private void InitLineChart()
        {
            option = new UILineOption();
            option.ToolTip.Visible = true;
            // 设置标题
            option.Title = new UITitle();
            option.Title.Text = "";
            option.Title.SubText = "";

            // 横坐标数据类型
            option.XAxisType = UIAxisType.Value;

            // 横坐标名称
            option.XAxis.Name = "时间/s";
            // 纵坐标名称
            option.YAxis.Name = "CO2浓度/ppm";
            option.XAxis.AxisLabel.DateTimeFormat = DateTimeEx.DateTimeFormat;

            #region 初始化三条线
            _lineSeries1 = option.AddSeries(new UILineSeries("Line1", Color.Blue));
            // 点的图标
            _lineSeries1.Symbol = UILinePointSymbol.None;
            // 图标大小
            _lineSeries1.SymbolSize = 4;
            // 折线宽度
            _lineSeries1.SymbolLineWidth = 2;
            // 图标颜色
            _lineSeries1.SymbolColor = Color.Blue;

            _lineSeries2 = option.AddSeries(new UILineSeries("Line2", Color.Green));
            // 点的图标
            _lineSeries2.Symbol = UILinePointSymbol.None;
            // 图标大小
            _lineSeries2.SymbolSize = 4;
            // 折线宽度
            _lineSeries2.SymbolLineWidth = 2;
            // 图标颜色
            _lineSeries2.SymbolColor = Color.Green;

            _lineSeries3 = option.AddSeries(new UILineSeries("Line3", Color.Red));
            // 点的图标
            _lineSeries3.Symbol = UILinePointSymbol.None;
            // 图标大小
            _lineSeries3.SymbolSize = 4;
            // 折线宽度
            _lineSeries3.SymbolLineWidth = 2;
            // 图标颜色
            _lineSeries3.SymbolColor = Color.Red;
            #endregion

            //// 设置系列1
            //series = option.AddSeries(new UILineSeries("Line1", Color.Blue));
            //float[] x = { 1, 2, 3, 4, 5, 7, 15 };
            //float[] y = { 2, 4, 6, 8, 10, 12, 14 };
            //for (int i = 0; i < x.Length; i++)
            //{
            //    series.Add(x[i], y[i]);
            //}
            //// 点的图标
            //series.Symbol = UILinePointSymbol.None;
            //// 图标大小
            //series.SymbolSize = 4;
            //// 折线宽度
            //series.SymbolLineWidth = 2;
            //// 图标颜色
            //series.SymbolColor = Color.Red;


            //// 设置系列2
            //series = option.AddSeries(new UILineSeries("Line2", Color.Green));

            //float[] x2 = { 1, 2, 3, 4, 5, 6, 7 };
            //float[] y2 = { 3, 6, 9, 12, 15, 18, 21 };
            //for (int i = 0; i < x.Length; i++)
            //{
            //    series.Add(x2[i], y2[i]);
            //}
            //// 点的图标
            //series.Symbol = UILinePointSymbol.None;
            //// 图标大小
            //series.SymbolSize = 4;
            //// 折线宽度
            //series.SymbolLineWidth = 2;
            //// 折线颜色
            //series.SymbolColor = Color.Red;
            //// 平滑曲线
            //series.Smooth = true;

            //// 设置纵坐标上限红线
            //option.GreaterWarningArea = new UILineWarningArea(3.5);
            //// 设置纵坐标下线黄线
            //option.LessWarningArea = new UILineWarningArea(2.2, Color.Gold);
            //option.YAxisScaleLines.Add(new UIScaleLine() { Color = Color.Red, Name = "上限", Value = 3.5 });
            //option.YAxisScaleLines.Add(new UIScaleLine() { Color = Color.Gold, Name = "下限", Value = 2.2 });


            //// 设置竖向的红线
            //option.XAxisScaleLines.Add(new UIScaleLine() { Color = Color.Red, Name = "x上界", Value = 50 });
            //option.XAxisScaleLines.Add(new UIScaleLine() { Color = Color.Red, Name = "x下界", Value = -50 });
            // 更新配置
            LineChart.SetOption(option);
        }

        //private void uiButton1_Click_1(object sender, EventArgs e)
        //{
        //    // 更新数据
        //    // 注意，两个系列的长度不要差太多，否则会抛出内存溢出的异常
        //    //UILineSeries serie = option.Series["Line1"];
        //    // 添加5个点
        //    for (int i = 0; i < 5; i++)
        //    {
        //        double newX = series.XData[series.XData.Count - 1] * 1.5;
        //        double newY = series.XData[series.YData.Count - 1] * 1.5;
        //        series.Add(newX, newY);
        //    }
        //    option.Series["Line1"] = series;
        //    LineChart.SetOption(option);
        //}

        private void uiButton1_Click(object sender, EventArgs e)
        {
            try
            {
                Form2 form2 = new Form2(uiLabel4.Text, uiLabel5.Text, uiLabel6.Text);
                form2.ShowDialog();
                uiLabel4.Text = form2.Name1;
                uiLabel5.Text = form2.Name2;
                uiLabel6.Text = form2.Name3;
                form2.Dispose();
            }
            catch(Exception ex)
            {
                UIMessageBox.Show(ex.Message);
            }
        }

        private void Form1_FormClosed(object sender, FormClosedEventArgs e)
        {
            try
            {
                if (serialPort != null)
                {
                    serialPort.closePort();
                }
            }
            catch (Exception ex)
            {
                UIMessageBox.Show(ex.Message);
            }
        }

        private void uiButton2_Click(object sender, EventArgs e)
        {
            try
            {
                if (uiButton2.Text == "打开串口")
                {
                    if (serialComboBox.SelectedItem == null)
                    {
                        UIMessageBox.Show("请先选择串口");
                        return;
                    }
                    try
                    {
                        if (serialPort != null)
                        {
                            serialPort.DataReceived -= SerialPort_DataReceived;
                        }
                        serialPort = new SerialClass(serialComboBox.SelectedItem as string);
                        serialPort.DataReceived += SerialPort_DataReceived;

                        uiButton2.Text = "关闭串口";
                        uiButton2.FillColor = Color.FromArgb(255, 160, 255);
                        uiButton2.FillSelectedColor = Color.FromArgb(229, 131, 229);
                        uiButton2.FillHoverColor = Color.FromArgb(229, 131, 229);
                    }
                    catch (Exception ex)
                    {
                        UIMessageBox.Show("打开串口错误: " + ex.Message);
                    }
                }
                else
                {
                    serialPort.closePort();
                    if (serialPort != null)
                    {
                        serialPort.DataReceived -= SerialPort_DataReceived;
                        serialPort = null;
                    }
                    uiButton2.Text = "打开串口";
                    uiButton2.FillColor = Color.FromArgb(80, 160, 255);
                    uiButton2.FillSelectedColor = Color.FromArgb(74, 131, 229);
                    uiButton2.FillHoverColor = Color.FromArgb(111, 168, 255);
                }
            }
            catch (Exception ex)
            {
                UIMessageBox.Show(ex.Message);
            }
        }

        private void SerialPort_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e, byte[] bits)
        {
            try
            {
                StringBuilder builder = new StringBuilder();
                foreach (var bit in bits)
                {
                    builder.Append(bit.ToString("X2"));
                    builder.Append(" ");
                }
                receivedTextBox.Text = builder.ToString();
                if (bits.Length >= 14)
                {
                    int value = bits[4] + bits[5] * 256;
                    var series = _lineSeries1;
                    switch (_testLineIndex)
                    {
                        case 1:
                            series = _lineSeries1;
                            break;
                        case 2:
                            series = _lineSeries2;
                            break;
                        case 3:
                            series = _lineSeries3;
                            break;
                    }
                    series.Add(_timeSum, value);
                    _thisData.Data.Add(value);
                    LineChart.SetOption(option);
                    DataManager.Instance.SaveData(_thisData);
                }
            }
            catch(Exception ex)
            {
                UIMessageBox.Show(ex.Message);
            }
        }

        private void uiButton3_Click(object sender, EventArgs e)
        {
            try
            {
                serialComboBox.Items.Clear();
                RegistryKey keyCom = Registry.LocalMachine.OpenSubKey("Hardware\\DeviceMap\\SerialComm");
                if (keyCom != null)
                {
                    string[] sSubKeys = keyCom.GetValueNames();
                    if (sSubKeys == null || sSubKeys.Length == 0)
                    {
                        UIMessageBox.Show("没有搜索到串口");
                    }
                    foreach (string sName in sSubKeys)
                    {
                        string sValue = (string)keyCom.GetValue(sName);
                        serialComboBox.Items.Add(sValue);
                    }
                    if (string.IsNullOrEmpty(serialComboBox.SelectedText) && serialComboBox.Items.Count > 0)
                    {
                        serialComboBox.SelectedIndex = 0;
                    }
                }
                else
                {
                    UIMessageBox.Show("没有搜索到串口");
                }
            }
            catch (Exception ex)
            {
                UIMessageBox.Show(ex.Message);
            }
        }

        private void timeComboBox_SelectedValueChanged(object sender, EventArgs e)
        {
            try
            {
                UIComboBox comboBox = sender as UIComboBox;
                switch (comboBox.SelectedItem)
                {
                    case "秒":
                        // 横坐标名称
                        option.XAxis.Name = "时间/s";
                        LineChart.SetOption(option);
                        return;
                    case "分":
                        option.XAxis.Name = "时间/min";
                        LineChart.SetOption(option);
                        return;
                    case "小时":
                        option.XAxis.Name = "时间/h";
                        LineChart.SetOption(option);
                        return;
                    default:
                        return;
                }
            }
            catch (Exception ex)
            {
                UIMessageBox.Show(ex.Message);
            }
        }

        private void startButton_Click(object sender, EventArgs e)
        {
            try
            {
                if (serialPort == null || !serialPort.IsOpen)
                {
                    UIMessageBox.Show("串口未连接，无法开始测试");
                    return;
                }

                if (string.IsNullOrWhiteSpace(sendTimeTextBox.Text))
                {
                    UIMessageBox.Show("时间不能为空");
                    return;
                }

                if (!int.TryParse(sendTimeTextBox.Text, out int time))
                {
                    UIMessageBox.Show("时间数格式不对");
                    return;
                }

                if (_isStartTest == false)
                {
                    timeComboBox.Enabled = false;
                    int num = 1000;
                    switch (timeComboBox.SelectedText)
                    {
                        case "秒":
                            num *= 1;
                            break;
                        case "分":
                            num *= 60;
                            break;
                        case "小时":
                            num *= 360;
                            break;
                    }

                    _thisData = new TestData();
                    _thisData.LineIndex = _testLineIndex;
                    _thisData.Frequency = time;
                    _thisData.FrequencyUnit = timeComboBox.SelectedText;
                    _thisData.StartDate = DateTime.Now;

                    _testTimer.Interval = num * time;
                    _testTimer.Start();
                    _isStartTest = true;
                    startButton.Text = "停止测试";
                    startButton.FillColor = Color.FromArgb(255, 160, 255);
                    startButton.FillSelectedColor = Color.FromArgb(229, 131, 229);
                    startButton.FillHoverColor = Color.FromArgb(229, 131, 229);
                }
                else
                {
                    _testTimer.Stop();
                    _isStartTest = false;
                    _testLineIndex++;
                    if (_testLineIndex > 3)
                    {
                        _testLineIndex = 1;
                    }
                    startButton.Text = "开始测试";
                    startButton.FillColor = Color.FromArgb(80, 160, 255);
                    startButton.FillSelectedColor = Color.FromArgb(74, 131, 229);
                    startButton.FillHoverColor = Color.FromArgb(111, 168, 255);
                    _timeSum = 0;
                }
            }
            catch(Exception ex)
            {
                UIMessageBox.Show(ex.Message);
            }
        }

        private void _testTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            try
            {
                if (serialPort != null && serialPort.IsOpen)
                {
                    string command = "64 69 03 5E 4E";
                    if (!string.IsNullOrWhiteSpace(sendTextBox.Text))
                    {
                        command = sendTextBox.Text;
                    }
                    serialPort.writeData(command);
                }
                _timeSum++;
            }
            catch(Exception ex)
            {
                UIMessageBox.Show(ex.Message);
            }
        }

        private void resetButton_Click(object sender, EventArgs e)
        {
            try
            {
                Form3 form3 = new Form3();
                form3.ShowDialog();

                if (form3.IsReset)
                {
                    // 还原数据
                    UILineSeries lineSeries = null;
                    var testData = form3.TestData;
                    switch (testData.LineIndex)
                    {
                        case 1:
                            lineSeries = _lineSeries1;
                            break;
                        case 2:
                            lineSeries = _lineSeries2;
                            break;
                        case 3:
                            lineSeries = _lineSeries3;
                            break;
                    }
                    _testLineIndex = testData.LineIndex + 1;
                    if (_testLineIndex > 3)
                    {
                        _testLineIndex = 1;
                    }

                    // 变动坐标轴
                    switch (testData.FrequencyUnit)
                    {
                        case "秒":
                            // 横坐标名称
                            option.XAxis.Name = "时间/s";
                            LineChart.SetOption(option);
                            break;
                        case "分":
                            option.XAxis.Name = "时间/min";
                            LineChart.SetOption(option);
                            break;
                        case "小时":
                            option.XAxis.Name = "时间/h";
                            LineChart.SetOption(option);
                            break;
                        default:
                            break;
                    }

                    // 确定频率
                    sendTimeTextBox.Text = testData.Frequency.ToString();

                    // 锁定坐标轴
                    timeComboBox.SelectedItem = testData.FrequencyUnit;
                    timeComboBox.Enabled = false;

                    lineSeries.Clear();
                    int count = 0;
                    foreach(int num in testData.Data)
                    {
                        lineSeries.Add(count * testData.Frequency, num);
                        count++;
                    }
                    LineChart.SetOption(option);
                }
                form3.Dispose();
            }
            catch(Exception ex)
            {
                UIMessageBox.Show(ex.Message);
            }
        }
    }
}
